<template>
  <div class="message-container" :class="{ 'user-message': isUser, 'ai-message': !isUser }">
    <div class="message-avatar">
      <el-avatar v-if="message.role === 'user'" icon="el-icon-user"></el-avatar>
      <div v-else class="custom-avatar">
        <img src="/boshi-logo.png" alt="博识智库" />
      </div>
    </div>
    <div class="message-content">
      <div class="message-sender">{{ isUser ? '我' : '博识智库' }}</div>
      
      <!-- 思考过程区块 (仅AI消息且有思考过程时显示) -->
      <div v-if="!isUser && thinking" class="thinking-block">
        <div class="thinking-header" @click="toggleThinking">
          <i class="el-icon-magic-stick"></i>
          思考过程
          <i :class="showThinking ? 'el-icon-arrow-down' : 'el-icon-arrow-right'"></i>
        </div>
        <div v-show="showThinking" class="thinking-content markdown-body" v-html="renderedThinking"></div>
      </div>
      
      <!-- 回答内容 -->
      <div class="message-text markdown-body">
        <div v-html="renderedMessage"></div>
      
        <!-- 参考知识区块 (集成进回答框) -->
        <div v-if="!isUser && message.sources && message.sources.length > 0" class="references-block">
          <div class="references-header" @click="toggleReferences">
            <i class="el-icon-document"></i>
            参考知识
            <i :class="showReferences ? 'el-icon-arrow-down' : 'el-icon-arrow-right'"></i>
          </div>
          <div v-show="showReferences" class="references-content">
            <div v-for="(source, index) in message.sources" :key="index" class="reference-item">
              <div class="reference-text">{{ source.text }}</div>
              <div v-if="source.relevance_percentage !== undefined" class="reference-score">
                相关度: <span class="percentage-badge">{{ source.relevance_percentage }}%</span>
              </div>
              <div v-else-if="source.relevance_score !== undefined" class="reference-score">
                相关度: <span class="percentage-badge">{{ Math.round(source.relevance_score * 100) }}%</span>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, computed } from 'vue';
import MarkdownIt from 'markdown-it';
import hljs from 'highlight.js';
// highlight.js样式已在main.js中全局导入

export default {
  name: 'ChatMessage',
  
  props: {
    message: {
      type: Object,
      required: true
    }
  },
  
  setup(props) {
    const isUser = computed(() => props.message.role === 'user');
    const showThinking = ref(false);
    const showReferences = ref(false);
    
    // 创建markdown-it实例
    const md = new MarkdownIt({
      html: true,
      linkify: true,
      typographer: true,
      highlight: function (str, lang) {
        if (lang && hljs.getLanguage(lang)) {
          try {
            return '<pre class="hljs"><code>' +
                   hljs.highlight(str, { language: lang, ignoreIllegals: true }).value +
                   '</code></pre>';
          } catch (__) {
            // 在空的catch块中添加注释，避免ESLint错误
            console.error('代码高亮出错');
          }
        }
        return '<pre class="hljs"><code>' + md.utils.escapeHtml(str) + '</code></pre>';
      }
    });
    
    // 处理消息内容
    const processContent = (text) => {
      if (!text) return '';
      
      // 对代码块进行特殊处理
      return text.replace(/```([\s\S]*?)```/g, (match) => {
        return match.replace(/\n/g, '⏎');
      }).replace(/\n/g, '\n\n').replace(/⏎/g, '\n');
    };
    
    // 检查是否包含思考过程（以<thinking>或<think>标记）
    const contentParts = computed(() => {
      const content = props.message.content || '';
      if ((content.includes('<thinking>') && content.includes('</thinking>')) || 
          (content.includes('<think>') && content.includes('</think>'))) {
        
        let thinkingMatch = content.match(/<thinking>([\s\S]*?)<\/thinking>/);
        if (!thinkingMatch) {
          thinkingMatch = content.match(/<think>([\s\S]*?)<\/think>/);
        }
        
        const thinking = thinkingMatch ? thinkingMatch[1].trim() : '';
        const answer = content
          .replace(/<thinking>[\s\S]*?<\/thinking>/, '')
          .replace(/<think>[\s\S]*?<\/think>/, '')
          .trim();
        
        return { thinking, answer };
      }
      return { thinking: '', answer: content };
    });
    
    const thinking = computed(() => contentParts.value.thinking);
    
    const renderedThinking = computed(() => {
      if (!thinking.value) return '';
      return md.render(processContent(thinking.value));
    });
    
    const renderedMessage = computed(() => {
      const content = isUser.value ? props.message.content : contentParts.value.answer;
      return md.render(processContent(content || ''));
    });
    
    const toggleThinking = () => {
      showThinking.value = !showThinking.value;
    };
    
    const toggleReferences = () => {
      showReferences.value = !showReferences.value;
    };
    
    return {
      isUser,
      thinking,
      showThinking,
      showReferences,
      renderedThinking,
      renderedMessage,
      toggleThinking,
      toggleReferences
    };
  }
}
</script>

<style>
/* 删除@import，改为在script中导入 */

/* Markdown样式 */
.markdown-body {
  font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Helvetica, Arial, sans-serif;
  font-size: 14px;
  line-height: 1.6;
  word-wrap: break-word;
}

.markdown-body pre {
  margin: 10px 0;
  border-radius: 5px;
  overflow: auto;
}

.markdown-body code {
  font-family: SFMono-Regular, Consolas, "Liberation Mono", Menlo, monospace;
  background-color: rgba(27, 31, 35, 0.05);
  border-radius: 3px;
  padding: 0.2em 0.4em;
  font-size: 85%;
}

.markdown-body pre > code {
  background-color: transparent;
  padding: 0;
  border-radius: 0;
}

.markdown-body h1, 
.markdown-body h2, 
.markdown-body h3, 
.markdown-body h4, 
.markdown-body h5, 
.markdown-body h6 {
  margin-top: 24px;
  margin-bottom: 16px;
  font-weight: 600;
  line-height: 1.25;
}

.markdown-body h1 {
  font-size: 2em;
  border-bottom: 1px solid #eaecef;
  padding-bottom: 0.3em;
}

.markdown-body h2 {
  font-size: 1.5em;
  border-bottom: 1px solid #eaecef;
  padding-bottom: 0.3em;
}

.markdown-body h3 {
  font-size: 1.25em;
}

.markdown-body p {
  margin-top: 0;
  margin-bottom: 16px;
}

.markdown-body blockquote {
  padding: 0 1em;
  color: #6a737d;
  border-left: 0.25em solid #dfe2e5;
  margin: 0 0 16px 0;
}

.markdown-body ul, 
.markdown-body ol {
  padding-left: 2em;
  margin-bottom: 16px;
}

.markdown-body table {
  display: block;
  width: 100%;
  overflow: auto;
  border-spacing: 0;
  border-collapse: collapse;
  margin-bottom: 16px;
}

.markdown-body table th,
.markdown-body table td {
  padding: 6px 13px;
  border: 1px solid #dfe2e5;
}

.markdown-body table tr {
  background-color: #fff;
  border-top: 1px solid #c6cbd1;
}

.markdown-body table tr:nth-child(2n) {
  background-color: #f6f8fa;
}
</style>

<style scoped>
.message-container {
  display: flex;
  margin-bottom: 24px;
  max-width: 90%;
}

.user-message {
  margin-left: auto;
  flex-direction: row-reverse;
  max-width: 70%;
}

.message-avatar {
  margin: 0 12px;
  flex-shrink: 0;
}

.custom-avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  overflow: hidden;
  display: flex;
  align-items: center;
  justify-content: center;
}

.custom-avatar img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

:deep(.el-avatar) {
  width: 40px;
  height: 40px;
}

/* 确保系统头像没有灰色蒙版 */
:deep(.ai-message .el-avatar) {
  background-color: transparent;
}

.message-content {
  display: flex;
  flex-direction: column;
  max-width: calc(100% - 70px);
}

.user-message .message-content {
  min-width: 200px;
}

.message-sender {
  font-size: 12px;
  color: #909399;
  margin-bottom: 4px;
}

.message-text {
  padding: 12px 16px;
  border-radius: 8px;
  font-size: 14px;
  line-height: 1.6;
  word-break: break-word;
  min-width: 150px;
}

.user-message .message-text {
  background-color: #ecf5ff;
  color: #303133;
}

.ai-message .message-text {
  background-color: #f4f4f5;
  color: #303133;
}

/* 思考过程样式 */
.thinking-block {
  margin-bottom: 8px;
  border-radius: 8px;
  overflow: hidden;
  border: 1px solid #e4e7ed;
}

.thinking-header {
  padding: 8px 12px;
  background-color: #f5f7fa;
  font-size: 13px;
  color: #606266;
  cursor: pointer;
  display: flex;
  align-items: center;
  gap: 5px;
}

.thinking-content {
  padding: 12px;
  background-color: #fffbe6;
  font-size: 13px;
  max-height: 500px;
  overflow-y: auto;
  border-top: 1px solid #e4e7ed;
}

/* 参考知识样式 */
.references-block {
  margin-top: 16px;
  border-radius: 8px;
  overflow: hidden;
  border: 1px solid #e4e7ed;
}

.references-header {
  padding: 8px 12px;
  background-color: #f0f9eb;
  font-size: 13px;
  color: #606266;
  cursor: pointer;
  display: flex;
  align-items: center;
  gap: 5px;
}

.references-content {
  padding: 12px;
  background-color: #f9f9f9;
  font-size: 13px;
  max-height: 300px;
  overflow-y: auto;
  border-top: 1px solid #e4e7ed;
}

.reference-item {
  padding: 8px;
  margin-bottom: 8px;
  background-color: #fff;
  border-radius: 4px;
  border: 1px solid #ebeef5;
}

.reference-item:last-child {
  margin-bottom: 0;
}

.reference-text {
  line-height: 1.5;
  color: #303133;
}

.reference-score {
  margin-top: 4px;
  font-size: 12px;
  color: #909399;
  text-align: right;
}

.percentage-badge {
  display: inline-block;
  padding: 2px 6px;
  border-radius: 10px;
  font-size: 11px;
  font-weight: bold;
  color: white;
  background-color: #409EFF;
}

/* 保留原有的message-sources但不显示，以保持兼容 */
.message-sources {
  display: none;
}
</style> 